package com.jams.goodox.activity.serve;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hangzhou.jin.customview.LoadView;
import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.activity.ScriptWebView;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.resp.PartyItemListResp;
import com.jams.goodox.entity.resp.PartyItemListResp.PartyItemData;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.EnterpriseService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;
import com.jams.library.widget.RecyclerDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;

import static com.jams.goodox.activity.ScriptWebView.NEWS_DETAIL;


/**
 * 根据PartyMemberServiceActivity ,用来展示4个不同的页面  (党员学习，党群活动，组织架构，公示)
 */
public class PartyServiceFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {


    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @Bind(R.id.lv_load)
    LoadView emptyView;
    @Bind(R.id.refresh)
    RefreshRecyclerView refreshRecyclerView;
    @Bind(R.id.srf)
    SwipeRefreshLayout srf;
    RecycleCommonAdapter<PartyItemData.PartyResultListBean> mAdapter;
    List<PartyItemData.PartyResultListBean> dataList = new ArrayList<>();
    
    private  final int REQUEST_CODE = 1991;
    public static  final int RESULT_CODE_PARTY = 2017;
    /**
     * 阅读数量
     */
    private  TextView tvReadNum;
    /**
     * 传入的typeid
     */
    private String typeId = "";
    /**
     * "0":党员服务,"1":***热点
     */
    private String serviceType = "";

    public static final String TYPE_SERVICE = "TYPE_SERVICE";

    private int curPage;

    public PartyServiceFragment() {
        // Required empty public constructor
    }

    /**
     * @param param1 传入的typeid
     * @param param2 "0":党员服务,"1":***热点
     */
    public static PartyServiceFragment newInstance(String param1, String param2) {
        PartyServiceFragment fragment = new PartyServiceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View contextView = inflater.inflate(R.layout.fragment_party, container, false);
        Bundle args = getArguments();
        typeId = StringUtils.newString(args.getString(ARG_PARAM1));
        serviceType = StringUtils.newString(args.getString(ARG_PARAM2));
        ButterKnife.bind(this, contextView);
        setData();
        return contextView;
    }

    /**
     * 数据设置
     */
    private void setData() {
        srf.setOnRefreshListener(this);
        refreshRecyclerView.setLayoutManager(new RefreshLinearLayoutManager(mActivity));
        refreshRecyclerView.setHasFixedSize(true);
        refreshRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter = new RecycleCommonAdapter<PartyItemData.PartyResultListBean>(mActivity, dataList, R.layout.item_listview_party_service) {
            @Override
            public void convert(RecycleCommonViewHolder helper, final PartyItemData.PartyResultListBean item, int position) {
                setItemData(helper, item);
            }
        };
        //增加headView
        View v = new View(mContext);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtil.dp2px(mContext, 8));
        v.setLayoutParams(params);
        mAdapter.setHeaderView(v);
        refreshRecyclerView.setAdapter(mAdapter);
        refreshRecyclerView.addItemDecoration(new RecyclerDivider(//分割线 1px
                mContext,
                LinearLayoutManager.VERTICAL,
                1,
                ContextCompat.getColor(getContext(),
                        R.color.shallow_divider)));
        refreshRecyclerView.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                requestData();
            }
        });
        onRefresh();
    }

    /**
     * 设置item 数据
     *
     * @param helper
     * @param item
     */
    private void setItemData(final RecycleCommonViewHolder helper, final PartyItemData.PartyResultListBean item) {
        helper.setSimpleDraweeView(R.id.sdv_icon, StringUtils.newString(item.coverUrl))
                .setText(R.id.tv_tittle, item.title)
                .setText(R.id.tv_time, item.createTime)
                .setText(R.id.tv_read_num, item.readNum >= 0 ? item.readNum + "": "0");//阅读数量不能小于0
        helper.setOnItemClickListener(new OnRecycleItemClickListener() {
            @Override
            public void itemClick() {
                tvReadNum = helper.getView(R.id.tv_read_num);
                Intent i = new Intent(mContext, ScriptWebView.class);
                i.putExtra("id", StringUtils.newString(item.id));
                i.putExtra("barTitle", "详情");
                i.putExtra(TYPE_SERVICE, StringUtils.newString(serviceType));
                startActivityForResult(i,REQUEST_CODE);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                try {
                    if (checkUiIsNull()) {
                        return;
                    }
                    srf.setRefreshing(true);
                    curPage = 1;
                    requestData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 请求网络数据
     */
    private void requestData() {
        final EnterpriseService service = createCallService(EnterpriseService.class);
        switch (serviceType) {
            case "0"://党员服务
                partyServiceData(service.getPartyItemList(typeId, curPage, AppConfig.PagSize));
                break;
            case "1"://***热点
                partyServiceData(service.getTownNewsItemList(typeId, curPage, AppConfig.PagSize));
                break;
            default:
                try {
                    srf.setRefreshing(false);
                    emptyView.loadCompleteNoData(R.mipmap.holder_no_common,R.string.no_content);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * 党员服务的数据
     */
    private void partyServiceData(Call<PartyItemListResp> call) {
        enqueue(call, new RetrofitCallbackListener<PartyItemListResp>() {
            @Override
            public void onSuccess(Call<PartyItemListResp> call, PartyItemListResp result) {
                try {
                    /* 滑动过快  SwipeRefreshLayout,RefreshRecyclerView 可能为null,
                       原因:EnterprisePolicyFragment快速切换,执行onDestroyView ,ButterKnife.unbind(this);srf,refreshRecyclerView,emptyView为空*/
                    if (checkUiIsNull()) {
                        return;
                    }
                    srf.setRefreshing(false);
                    refreshRecyclerView.loadMoreComplete();
                    if (result.data != null) {
                        if (curPage == 1) {
                            dataList.clear();
                        }
                        if (result.data.pageInfo == null) {
                            refreshRecyclerView.setCanLoadMore(false);
                        } else {
                            refreshRecyclerView.setCanLoadMore(result.data.pageInfo.hasMore);
                        }
                        dataList.addAll(result.data.resultList);
                        curPage++;
                        refreshRecyclerView.notifyData();
                    }
                    if (!CollectionUtils.hasData(dataList)) {
                        emptyView.loadCompleteNoData(R.mipmap.holder_no_common,R.string.no_content);
                    } else {
                        emptyView.loadComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String msg) {
                try {
                    if (checkUiIsNull()) {
                        return;
                    }
                    srf.setRefreshing(false);
                    refreshRecyclerView.loadMoreComplete();
                    if (!CollectionUtils.hasData(dataList)) {
                        emptyView.loadCompleteNoData(R.mipmap.holder_no_common,R.string.no_content);
                    } else {
                        emptyView.loadComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    //判断控件是否为空
    private boolean checkUiIsNull(){
        return (emptyView == null || srf == null || refreshRecyclerView == null );
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE){
            if(resultCode == RESULT_CODE_PARTY){
                int after = data.getIntExtra(NEWS_DETAIL,0);
                Integer before =  Integer.valueOf(tvReadNum.getText().toString());
                if (after > before) {
                    tvReadNum.setText(after+"");//如果之后的阅读量(从详情页获得) 大于 之前的阅读量 ,则重置阅读数量,反之则不重置
                }
                
            }
        }
    }
}
